package priv.solution.leetcode;

public class Solution {
    public static void main(String[] args) {
        ListNode head = genList();

        print(head);

        int i = 25;
        while (i-- > 0) {
            head = genList();
            ListNode head1 = new Solution().reverseKGroup(head, i);
            System.out.println("i = " + i);
            print(head1);
        }

    }

    private static ListNode genList() {
        ListNode head = new ListNode(1);

        ListNode node = head;
        for (int i = 0; i < 23; i++) {
            node.next = new ListNode(node.val + 1);
            node = node.next;
        }
        return head;
    }

    private static void print(ListNode head) {
        int i = 0;
        while (head != null) {
            System.out.print(head.val + ",");
            head = head.next;
            i++;
            if (i >= 30) {
                i = 0;
                System.out.println();
            }
        }
        System.out.println("===end====");
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (k <= 1) {
            return head;
        }

        ListNode[] ary = new ListNode[k];
        ListNode nextHead = head;
        ListNode preTail = null;
        while (nextHead != null) {
            int index = 0;
            while (nextHead != null && index < k) {
                ary[index++] = nextHead;
                nextHead = nextHead.next;
            }
            if (index == k) {
                while (index-- > 1) {
                    ary[index].next = ary[index - 1];
                }
                if (preTail == null) {
                    head = ary[k - 1];
                } else {
                    preTail.next = ary[k - 1];
                }
                preTail = ary[0];
                preTail.next = null;
            } else {
                if (preTail == null) {
                    return head;
                } else {
                    preTail.next = ary[0];
                }
            }
        }
        return head;
    }
}


class ListNode {
    int val;
    ListNode next;

    ListNode(int x) {
        val = x;
    }
}
